<template>
  <view class="fixed inset-0 flex flex-col overflow-hidden bg-white">
    <!-- 固定头部区域 -->
    <view class="flex-shrink-0">
      <S1Header title="买家列表" :on-back="navigateBack">
        <template #right>
          <view class="flex items-center" @click="onFilter">
            <image class="mr-8rpx h-32rpx w-32rpx" src="https://ceshiweb.picaime.com/static/images/filter.png" />
            <text class="text-28rpx text-[#007aff]">
              筛选
            </text>
          </view>
        </template>
      </S1Header>

      <view class="flex items-center border-b-1 border-b-[#f5f5f5] bg-[#f8f8f8] p-20rpx">
        <view
          class="mr-10rpx h-40rpx w-40rpx bg-[url('https://ceshiweb.picaime.com/static/images/search.png')] bg-contain bg-center bg-no-repeat"
        />
        <input
          v-model="keyword" class="h-40rpx flex-1 border-none bg-transparent text-26rpx outline-none"
          placeholder="搜索买家名称或手机号" confirm-type="search" @confirm="onSearch"
        >
      </view>

      <view class="flex flex-row bg-[#f5f5f5] p-20rpx">
        <text class="mr-30rpx text-28rpx text-[#ff7f0a] font-bold">
          总赊欠：{{ formatNumber(totalOwed) }}
        </text>
        <text class="text-28rpx text-[#333333]">
          ，共{{ totalBuyers }}个买家
        </text>
      </view>
    </view>

    <!-- 可滑动区域 -->
    <scroll-view scroll-y class="h-80vh" :show-scrollbar="false" @scrolltolower="loadMore">
      <view class="pb-20rpx">
        <u-empty
          v-if="buyers.length === 0 && !loading" mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png"
          text="暂无买家数据"
        />

        <u-loadmore v-if="loading" status="loading" />

        <view v-if="buyers.length > 0" class="flex flex-col">
          <view v-for="(buyer, index) in buyers" :key="buyer.id || index" class="relative p-24rpx">
            <view class="flex items-center justify-between">
              <view class="flex flex-1 flex-col">
                <!-- 头部：买家名称和电话 -->
                <view class="mb-16rpx flex items-center">
                  <text class="text-34rpx text-[#333] font-bold">
                    {{ buyer.maijia }}
                  </text>
                  <!-- 注释掉暂不存在的phone属性 -->
                  <!-- <text v-if="buyer.phone" class="text-28rpx text-[#666] ml-16rpx">{{ formatPhone(buyer.phone) }}</text> -->
                </view>

                <!-- 中部：赊欠限制 -->
                <view class="mb-16rpx">
                  <text class="text-26rpx text-[#999]">
                    赊欠限制：{{ buyer.no_pay_num }}单
                  </text>
                </view>

                <!-- 底部：赊欠金额和天数标签 -->
                <view class="flex items-center">
                  <text class="mr-12rpx text-28rpx">
                    已赊欠：<text class="text-[#ff7f0a] font-semibold">
                      {{ formatNumber(buyer.no_pay_total) }}元
                    </text>
                  </text>
                  <view
                    class="ml-4rpx rounded-4rpx px-16rpx py-4rpx"
                    :class="Number(buyer.sheqian_day) > 30 ? 'bg-[#ff4949]/10' : 'bg-[#13CE66]/10'"
                  >
                    <text
                      :class="Number(buyer.sheqian_day) > 30 ? 'text-[#ff4949]' : 'text-[#13CE66]'"
                      class="text-24rpx font-medium"
                    >
                      {{ buyer.sheqian_day || 0 }}天
                    </text>
                  </view>
                  <view class="ml-auto flex items-center" @click="goDetail(buyer)">
                    <text class="mr-8rpx text-26rpx text-[#007aff]">
                      详情
                    </text>
                    <image class="h-32rpx w-32rpx" src="https://ceshiweb.picaime.com/static/images/report/right.png" />
                  </view>
                </view>
              </view>

              <!-- 右侧状态标签 -->
              <view
                v-if="getConsumptionStatus(buyer)"
                class="absolute right-0 top-12rpx rounded-l-6rpx px-16rpx py-8rpx" :class="getBadgeColorClass(buyer)"
              >
                <text class="text-24rpx text-white font-medium">
                  {{ getConsumptionStatus(buyer) }}
                </text>
              </view>
            </view>
            <view class="mt-24rpx h-1rpx bg-[#f5f5f5]" />
          </view>
        </view>

        <!-- 加载更多 -->
        <u-loadmore v-if="buyers.length > 0 && !loading" :status="loadStatus" @loadmore="loadMore" />
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import type { MemberItem } from '@/api/member/types';
import { computed, onMounted, ref } from 'vue';
import { MemberApi } from '@/api';
import * as S1Header from '@/components/S1Header.vue';
import usePermission from '@/hooks/use-permission';

// 检查权限
onShow(() => {
  usePermission();
});

// 页面状态
const keyword = ref('');
const loading = ref(false);
const page = ref(1);
const perPage = ref(15);
const total = ref(0);
const lastPage = ref(1);
const totalOwed = ref(0);
const totalBuyers = ref(0);
const buyers = ref<MemberItem[]>([]);

// 加载状态：loading-加载中，nomore-没有更多了，loadmore-加载更多
const loadStatus = computed(() => {
  if (loading.value) return 'loading';
  if (page.value >= lastPage.value) return 'nomore';
  return 'loadmore';
});

// 获取买家列表数据
const fetchData = async (isRefresh = false) => {
  try {
    loading.value = true;

    if (isRefresh) {
      page.value = 1;
    }

    const params = {
      page: page.value,
      limit: perPage.value,
      keyword: keyword.value || undefined,
    };

    const res = await MemberApi.getMemberLists(params);

    if (res.code === 200) {
      // 更新总计数据
      totalOwed.value = res.data.total_price || 0;
      totalBuyers.value = res.data.total_num || 0;

      // 设置分页信息
      total.value = res.data.data.total;
      lastPage.value = res.data.data.last_page;

      // 更新买家列表
      if (isRefresh) {
        buyers.value = res.data.data.data;
      }
      else {
        buyers.value = [...buyers.value, ...res.data.data.data];
      }
    }
    else {
      uni.showToast({
        title: res.msg || '获取买家列表失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('获取买家列表失败', error);
    uni.showToast({
      title: '获取买家列表失败',
      icon: 'none',
    });
  }
  finally {
    loading.value = false;
  }
};

// 加载更多数据
const loadMore = () => {
  if (page.value < lastPage.value) {
    page.value++;
    fetchData();
  }
};

// 搜索
const onSearch = () => {
  fetchData(true);
};

// 筛选
const onFilter = () => {
  uni.showToast({
    title: '筛选功能开发中',
    icon: 'none',
  });
};

// 格式化数字(添加千分位)
const formatNumber = (num: number) => {
  return num.toLocaleString();
};

// 获取消费状态
const getConsumptionStatus = (buyer: MemberItem) => {
  if (!buyer.no_order_day && buyer.no_order_day !== 0) return '';

  const days = Number(buyer.no_order_day);
  if (days === 0) return '今日已消费';
  if (days <= 7) return `${days}日未消费`;
  if (days <= 30) return '7日未消费';
  return '30日未消费';
};

// 获取消费状态颜色类
const getBadgeColorClass = (buyer: MemberItem) => {
  if (!buyer.no_order_day && buyer.no_order_day !== 0) return '';

  const days = Number(buyer.no_order_day);
  if (days === 0) return 'bg-[#13CE66]'; // 绿色
  if (days <= 7) return 'bg-[#FFA500]'; // 橙色 - 7日未消费
  if (days <= 30) return 'bg-[#FFA500]'; // 橙色 - 30日未消费
  return 'bg-[#FF4949]'; // 红色
};

// 获取消费状态颜色
const getConsumptionStatusColor = (buyer: MemberItem) => {
  if (!buyer.no_order_day && buyer.no_order_day !== 0) return '';

  const days = Number(buyer.no_order_day);
  if (days === 0) return '#13CE66'; // 绿色
  if (days <= 30) return '#FFA500'; // 橙色
  return '#FF4949'; // 红色
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 查看买家详情
const goDetail = (buyer: MemberItem) => {
  // 跳转到赊欠订单页面
  uni.navigateTo({
    url: `/pages/common/creditOrderList/creditOrderList?maijia_id=${buyer.maijia_id}`,
  });
};

// 页面初始化时加载数据
onMounted(() => {
  fetchData(true);
});
</script>

<style scoped>
:deep(uni-page-body) {
  height: 100%;
  overflow: hidden;
}
</style>
